package com.hckjsec.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hckjsec.cloud.domain.*;
import com.hckjsec.cloud.domain.jishiban.InterfaceBackUser;
import com.hckjsec.cloud.domain.videoView.DetectAuthView;
import com.hckjsec.cloud.domain.videoView.WebSocketUser;
import com.hckjsec.cloud.domain.view.*;
import com.hckjsec.cloud.domain.webSite.WebSiteIntoView;
import com.hckjsec.cloud.domain.wechatDataView.*;
import com.hckjsec.cloud.domain.wechatView.*;
import com.hckjsec.cloud.enums.BasicParamEnum;
import com.hckjsec.cloud.enums.publicParamEnum;
import com.hckjsec.cloud.message.SendWxMessage;
import com.hckjsec.cloud.message.TempToken;
import com.hckjsec.cloud.service.*;
import com.hckjsec.common.config.BdIdCardResult;
import com.hckjsec.common.config.FileInfoView;
import com.hckjsec.common.config.JeeThinkConfig;
import com.hckjsec.common.constant.Constants;
import com.hckjsec.common.core.controller.BaseController;
import com.hckjsec.common.core.domain.entity.SysDictData;
import com.hckjsec.common.core.page.TableDataInfo;
import com.hckjsec.common.core.redis.RedisCache;
import com.hckjsec.common.core.redis.SerialNumberUtils;
import com.hckjsec.common.dto.Result;
import com.hckjsec.common.enums.NumbereEnum;
import com.hckjsec.common.enums.SysFileTypeEnum;
import com.hckjsec.common.image.CenerateSignImage;
import com.hckjsec.common.init.YwInitData;
import com.hckjsec.common.qiyuesuo.QysUser;
import com.hckjsec.common.qiyuesuo.SendByCodeSetting;
import com.hckjsec.common.utils.*;
import com.hckjsec.common.utils.bean.BeanUtils;
import com.hckjsec.common.utils.file.FileUploadUtils;
import com.hckjsec.common.utils.http.HttpUtils;
import com.hckjsec.common.utils.sign.Base64Converter;
import com.hckjsec.common.utils.uuid.BdOrcUtil;
import com.hckjsec.common.utils.uuid.IdUtils;
import com.hckjsec.system.domain.SysMatter;
import com.hckjsec.system.service.ISysDictTypeService;
import com.hckjsec.system.service.ISysMatterService;
import com.hckjsec.website.domain.view.WebSiteView;
import com.qiyuesuo.sdk.v2.SdkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 此类处理微信小程序端请求的接口数据
 */
@RestController
@RequestMapping("/wechat/api")
public class WxPublicApiController extends BaseController {
    @Autowired
    private YwInitData ywInitData;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IAppletsWechatUserService appletsWechatUserService;
    @Autowired
    private IAppletsConfigParamService appletsConfigParamService;
    @Autowired
    private IAppletsApplicantUserService appletsApplicantUserService;
    @Autowired
    private IAppletsConfigMatterDetailService appletsConfigMatterDetailService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private ISysCountryService sysCountryService;
    @Autowired
    private ISysCountryIanguagesService sysCountryIanguagesService;
    @Autowired
    private IAppletsPublicParamService appletsPublicParamService;
    @Autowired
    private IAppletsConfigMatterService appletsConfigMatterService;
    @Autowired
    private ISysMatterService sysMatterService;
    @Autowired
    private IAppletsBusinessService appletsBusinessService;
    @Autowired
    private IAppletsBusinessMatterService appletsBusinessMatterService;
    @Autowired
    private IAppletsBusinessMatterApplicantService appletsBusinessMatterApplicantService;
    @Autowired
    private IAppletsBusinessMaterialService appletsBusinessMaterialService;
    @Autowired
    private IAppletsBusinessCostService appletsBusinessCostService;
    @Autowired
    private IAppletsBusinessVideoService appletsBusinessVideoService;
    @Autowired
    private IAppletsBusinessVideoUserService appletsBusinessVideoUserService;
    @Autowired
    private WxAsyncService wxAsyncService;
    @Autowired
    private IAppletsBusinessVideoSigncoorService appletsBusinessVideoSigncoorService;
    @Autowired
    private IAppletsBusinessVideoSignService appletsBusinessVideoSignService;
    @Autowired
    private IAppletsBusinessReserveService appletsBusinessReserveService;
    @Autowired
    private IAppletsApplicantUserLogService appletsApplicantUserLogService;
    @Autowired
    private WxSendTplMessageService wxSendTplMessageService;
    @Autowired
    private IWebWebsiteUserService webWebsiteUserService;
    @Autowired
    private IAppletsBusinessConsultingService appletsBusinessConsultingService;
    /**
     * 小程序端初始化
     * @author cyt
     * @date 2021-06-23
     */
    @PostMapping("/global")
    public Result global(@RequestBody WechatView wechatView)
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
             return Result.cloud_602("appId不能为空");
        }
        GlobalView globalView = new GlobalView();
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        BasicView basicView=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(configId)),BasicView.class);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        globalView.setAppletsConfig(appletsConfig);
        globalView.setBasicView(basicView);
        Map<String,String> resState = JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigStateMap().get(configId)),Map.class);
        globalView.setIsurgent(resState.get(BasicParamEnum.SYS_APPLETS_BASIC_URGENT.getKey()) == null?"false":resState.get(BasicParamEnum.SYS_APPLETS_BASIC_URGENT.getKey()));
        globalView.setIsmail(resState.get(BasicParamEnum.SYS_APPLETS_BASIC_MAIL.getKey()) == null?"false":resState.get(BasicParamEnum.SYS_APPLETS_BASIC_MAIL.getKey()));
        globalView.setIsattestation(resState.get(BasicParamEnum.SYS_APPLETS_BASIC_ATTESTATION.getKey()) == null?"false":resState.get(BasicParamEnum.SYS_APPLETS_BASIC_ATTESTATION.getKey()));
        globalView.setIslivingthing(resState.get(BasicParamEnum.SYS_APPLETS_BASIC_LIVINGTHING.getKey()) == null?"false":resState.get(BasicParamEnum.SYS_APPLETS_BASIC_LIVINGTHING.getKey()));
        globalView.setIspayment(resState.get(BasicParamEnum.SYS_APPLETS_BASIC_PAYMENT.getKey()) == null?"false":resState.get(BasicParamEnum.SYS_APPLETS_BASIC_PAYMENT.getKey()));
        AppletsPublicParam specifyData=new AppletsPublicParam();
        specifyData.setDeptId(appletsConfig.getDeptId());
        specifyData.setParamType(publicParamEnum.APPLETS_PUBLIC_PARAM_SPECIFY.getKey());
        List<AppletsPublicParam> specifyDataList=appletsPublicParamService.selectAppletsPublicParamList(specifyData);
        if (!StringUtils.isNull(specifyDataList) && specifyDataList.size()>0){
            globalView.setIsappointedNotary("true");
        }else{
            globalView.setIsappointedNotary("false");
        }
        return Result.success(globalView);
    }

    /**
     * 小程序端人员注册
     * @author cyt
     * @date 2021-06-23
     */
    @PostMapping("/checkUser")
    public Result checkUser(@RequestBody WxUserLoginView wxUserLoginView)
    {
        String appid = StringUtils.isHcNull(wxUserLoginView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        //1.通过微信接口换取openid
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        String rspStr = HttpUtils.sendGet(ComUtil.WX_API_BASE+ComUtil.WX_GETUSER, "appid="+wxUserLoginView.getAppid()+"&secret="+appletsConfig.getAppsecret()+"&js_code="+wxUserLoginView.getJs_code()+"&grant_type=authorization_code", Constants.UTF8);
        JSONObject reuslt = JSON.parseObject(rspStr);
        String session_key = String.valueOf(reuslt.get("session_key"));
        String openid = String.valueOf(reuslt.get("openid"));
        if("".equals(StringUtils.isHcNull(openid,"")) || "null".equals(StringUtils.isHcNull(openid,""))){
            return Result.cloud_602("openid获取失败");
        }
        String decrypt=WxDecodeUtils.wxDecrypt(wxUserLoginView.getEncrypted(),session_key,wxUserLoginView.getIv());
        AppletsWechatUser wechatUser=JSON.parseObject(decrypt,AppletsWechatUser.class);
        AppletsWechatUser appletsWechatUser = new AppletsWechatUser(openid,appletsConfig.getId(),appletsConfig.getDeptId(),StringUtils.isHcNull(wxUserLoginView.getLocation().getLongitude(),""),StringUtils.isHcNull(wxUserLoginView.getLocation().getLatitude(),""));
        appletsWechatUser.setAreatype("1");
        if (reuslt.containsKey("unionid")){
            appletsWechatUser.setUnionid(String.valueOf(reuslt.get("unionid")));
        }
        if (StringUtils.isNull(wechatUser)){
            appletsWechatUser.setNickname("微信用户");
        }else{
            String[] nullPropertyNames = BeanUtils.getNullPropertyNames(wechatUser);
            BeanUtils.copyProperties(wechatUser,appletsWechatUser,nullPropertyNames);
        }
        AppletsWechatUser appletsWechatUserData = appletsWechatUserService.selectAppletsWechatUserById(openid);
        if(StringUtils.isNull(appletsWechatUserData)){//库里无数据 进行添加
            appletsWechatUserService.insertAppletsWechatUser(appletsWechatUser);
        }else{
            if("微信用户".equals(appletsWechatUser.getNickname())){
                appletsWechatUser.setNickname(appletsWechatUserData.getNickname());
            }
            appletsWechatUserService.updateAppletsWechatUser(appletsWechatUser);
        }
        //如果小程序端人员已注册  则直接注册
        AppletsWechatUser oldAppletsWechatUser = appletsWechatUserService.selectAppletsWechatUserById(openid);
        String unionid = StringUtils.isHcNull(oldAppletsWechatUser.getUnionid(),"");
        if (!"".equals(unionid)){
            AppletsApplicantUser appletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
            if (StringUtils.isNull(appletsApplicantUser)){
                AppletsWechatUser oldAppletsWechatUserData = new AppletsWechatUser();
                oldAppletsWechatUserData.setUnionid(unionid);
                List<AppletsWechatUser>  oldAppletsWechatUserList = appletsWechatUserService.selectAppletsWechatUserList(oldAppletsWechatUserData);
                AtomicReference<Boolean> atomicReference = new AtomicReference<>(true);
                oldAppletsWechatUserList.forEach(kv->{
                    String oldOpenid = kv.getOpenid();
                    if (!openid.equals(oldOpenid)){
                        AppletsApplicantUser oldAppletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(oldOpenid);
                        if (!StringUtils.isNull(oldAppletsApplicantUser) && atomicReference.get()){
                            oldAppletsApplicantUser.setConfigId(appletsConfig.getId());
                            oldAppletsApplicantUser.setDeptId(appletsConfig.getDeptId());
                            oldAppletsApplicantUser.setOpenid(openid);
                            oldAppletsApplicantUser.setAreatype("1");
                            int rows = appletsApplicantUserService.insertAppletsApplicantUser(oldAppletsApplicantUser);
                            if (rows > 0){
                                atomicReference.set(false);
                            }
                        }
                    }
                });
            }
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,true);
        appletsApplicantUserLogService.insertLong(openid,"登录小程序，获取用户授权");
        return Result.success(openidView);
    }
    /**
     * 公众号端人员注册
     * @author cyt
     * @date 2021-06-23
     */
    @PostMapping("/checkGzhUser")
    public Result checkGzhUser(@RequestBody WxUserLoginView wxUserLoginView)
    {
        String appid = StringUtils.isHcNull(wxUserLoginView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        //1.通过微信接口换取openid
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        String rspStr = HttpUtils.sendGet(ComUtil.WX_API_BASE+ComUtil.WX_GETUSER_GZH, "appid="+wxUserLoginView.getAppid()+"&secret="+appletsConfig.getAppsecret()+"&code="+wxUserLoginView.getCode()+"&grant_type=authorization_code", Constants.UTF8);
        JSONObject reuslt = JSON.parseObject(rspStr);
        String openid = String.valueOf(reuslt.get("openid"));
        String access_token = String.valueOf(reuslt.get("access_token"));
        if("".equals(StringUtils.isHcNull(openid,"")) || "null".equals(StringUtils.isHcNull(openid,""))){
            return Result.cloud_602("openid获取失败");
        }
        TempToken tempToken = new TempToken(appletsConfig.getAppid(),appletsConfig.getAppsecret());
        tempToken.setOpenid(openid);
        tempToken.setAccess_token(access_token);
        String mJson = HttpUtils.sendGet(ComUtil.WX_API_BASE+ComUtil.WX_GETUNIONID2_GZH, "access_token="+access_token+"&openid="+openid+"&code="+wxUserLoginView.getCode()+"&lang=zh_CN", Constants.UTF8);
        JSONObject msgJson=JSON.parseObject(mJson);
        AppletsWechatUser appletsWechatUser = new AppletsWechatUser(openid,appletsConfig.getId(),appletsConfig.getDeptId(),"","");
        appletsWechatUser.setAreatype("0");
        if (msgJson.containsKey("unionid")){
            appletsWechatUser.setUnionid(String.valueOf(msgJson.get("unionid")));
        }
        if (msgJson.containsKey("nickname")){
            appletsWechatUser.setNickname(String.valueOf(msgJson.get("nickname")));
        }
        if (msgJson.containsKey("headimgurl")){
            appletsWechatUser.setAvatarurl(String.valueOf(msgJson.get("headimgurl")));
        }
        if (msgJson.containsKey("sex")){
            appletsWechatUser.setGender(String.valueOf(msgJson.get("sex")));
        }
        AppletsWechatUser appletsWechatUserData = appletsWechatUserService.selectAppletsWechatUserById(openid);
        if(StringUtils.isNull(appletsWechatUserData)){//库里无数据 进行添加
            appletsWechatUserService.insertAppletsWechatUser(appletsWechatUser);
        }else{
            if (msgJson.containsKey("unionid")){
                appletsWechatUserData.setUnionid(String.valueOf(msgJson.get("unionid")));
            }
            if (msgJson.containsKey("nickname")){
                appletsWechatUserData.setNickname(String.valueOf(msgJson.get("nickname")));
            }
            if (msgJson.containsKey("headimgurl")){
                appletsWechatUserData.setAvatarurl(String.valueOf(msgJson.get("headimgurl")));
            }
            if (msgJson.containsKey("sex")){
                appletsWechatUserData.setGender(String.valueOf(msgJson.get("sex")));
            }
            appletsWechatUserService.updateAppletsWechatUser(appletsWechatUserData);
        }
        //如果小程序端人员已注册  则直接注册
        AppletsWechatUser oldAppletsWechatUser = appletsWechatUserService.selectAppletsWechatUserById(openid);
        String unionid = "";
        if(StringUtils.isNotNull(appletsWechatUser)){
            unionid = StringUtils.isHcNull(appletsWechatUser.getUnionid(),"");
        }
        if (!"".equals(unionid)){
            AppletsApplicantUser appletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
            if (StringUtils.isNull(appletsApplicantUser)){
                AppletsWechatUser oldAppletsWechatUserData = new AppletsWechatUser();
                oldAppletsWechatUserData.setUnionid(unionid);
                List<AppletsWechatUser>  oldAppletsWechatUserList = appletsWechatUserService.selectAppletsWechatUserList(oldAppletsWechatUserData);
                AtomicReference<Boolean> atomicReference = new AtomicReference<>(true);
                oldAppletsWechatUserList.forEach(kv->{
                    String oldOpenid = kv.getOpenid();
                    if (!openid.equals(oldOpenid)){
                        AppletsApplicantUser oldAppletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(oldOpenid);
                        if (!StringUtils.isNull(oldAppletsApplicantUser) && atomicReference.get()){
                            oldAppletsApplicantUser.setConfigId(appletsConfig.getId());
                            oldAppletsApplicantUser.setDeptId(appletsConfig.getDeptId());
                            oldAppletsApplicantUser.setOpenid(openid);
                            oldAppletsApplicantUser.setAreatype("0");
                            int rows = appletsApplicantUserService.insertAppletsApplicantUser(oldAppletsApplicantUser);
                            if (rows > 0){
                                atomicReference.set(false);
                            }
                        }
                    }
                });
            }
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,true);
        return Result.success(openidView);
    }
    //公众号端百度OCR
    @PostMapping("/idGzhCardOcr")
    public Result idGzhCardOcr(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String filePath = StringUtils.isHcNull(wechatView.getFilePath(),"");
        if("".equals(filePath)){
            return Result.cloud_602("filePath不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        BasicView basicView=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(openidView.getConfigId())),BasicView.class);
        FileInfoView fileInfoView= new FileInfoView();
        fileInfoView.setPathFileName(JeeThinkConfig.getProfile()+filePath);
        BdIdCardResult idCardInfo = BdOrcUtil.getIdCardInfo("front",fileInfoView.getPathFileName(),basicView.getBdocr().getAppid(),basicView.getBdocr().getAppkey(),basicView.getBdocr().getAppsecret());
        return Result.success(idCardInfo);
    }

    //验证用户是否注册
    @PostMapping("/isregisterUser")
    public Result isregisterUser(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        boolean flag=false;
        AppletsApplicantUser appletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
        if (!StringUtils.isNull(appletsApplicantUser)){
            flag=true;
        }else{
            flag=false;
        }
        Result ajax = Result.success();
        ajax.put("isInformation",flag);
        return Result.success(ajax);
    }

    //用户注册
    @PostMapping("/registerUser")
    public Result registerUser(@RequestBody AppletsApplicantUser appletsApplicantUser)
    {
        String content="";
        //出生日期计算
        String certificateNo=StringUtils.isHcNull(appletsApplicantUser.getCertificatesnumber(),"");
        if(!"".equals(certificateNo)){
            certificateNo = certificateNo.toUpperCase();
            String birthday=ComUtil.getBirAgeSex(certificateNo).get("birthday");
            if(!"".equals(StringUtils.isHcNull(birthday,""))){
                appletsApplicantUser.setBorntime(birthday);
            }
        }
        String openid = StringUtils.isHcNull(appletsApplicantUser.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView=appletsApplicantUserService.getOpenidView(openid,false);
        appletsApplicantUser.setAreatype(openidView.getAreatype());
        appletsApplicantUser.setDeptId(openidView.getDeptId());
        appletsApplicantUser.setConfigId(openidView.getConfigId());
        int rows=0;
        String isself = StringUtils.isHcNull(appletsApplicantUser.getIsself(),"");
        if ("TRUE".equals(isself.toUpperCase())){//微信用户注册
            appletsApplicantUser.setIsself("TRUE");
            AppletsApplicantUser appletsApplicantUserB=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
            if (StringUtils.isNull(appletsApplicantUserB)) {
                content="["+appletsApplicantUser.getName()+"]用户信息注册。";
                rows=appletsApplicantUserService.insertAppletsApplicantUser(appletsApplicantUser);
            }else{
                content="["+appletsApplicantUser.getName()+"]用户信息修改。";
                appletsApplicantUser.setId(appletsApplicantUserB.getId());
                rows=appletsApplicantUserService.updateAppletsApplicantUser(appletsApplicantUser);
            }
            if (rows>0){
                appletsApplicantUserService.getOpenidView(openid,true);
            }
        }else{
            appletsApplicantUser.setIsself("FALSE");
            if (StringUtils.isNull(appletsApplicantUser.getId())) {
                content="添加申请人["+appletsApplicantUser.getName()+"]。";
                rows=appletsApplicantUserService.insertAppletsApplicantUser(appletsApplicantUser);
            }else{
                content="修改申请人["+appletsApplicantUser.getName()+"]信息。";
                rows=appletsApplicantUserService.updateAppletsApplicantUser(appletsApplicantUser);
            }
        }
        //如果存在同时有小程序和公众号情况  就新增或修改人员
        AppletsWechatUser appletsWechatUser = appletsWechatUserService.selectAppletsWechatUserById(openid);
        String unionid = "";
        if(StringUtils.isNotNull(appletsWechatUser)){
            unionid = StringUtils.isHcNull(appletsWechatUser.getUnionid(),"");
        }
        if (!"".equals(unionid) && "TRUE".equals(isself.toUpperCase())){
            AppletsWechatUser oldAppletsWechatUserData = new AppletsWechatUser();
            oldAppletsWechatUserData.setUnionid(unionid);
            List<AppletsWechatUser>  oldAppletsWechatUserList = appletsWechatUserService.selectAppletsWechatUserList(oldAppletsWechatUserData);
            AppletsApplicantUser findAppletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
            oldAppletsWechatUserList.forEach(kv->{
                String oldOpenid = kv.getOpenid();
                if (!openid.equals(oldOpenid)){
                    AppletsApplicantUser oldAppletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(oldOpenid);
                    if (StringUtils.isNull(oldAppletsApplicantUser)){
                        findAppletsApplicantUser.setConfigId(kv.getConfigId());
                        findAppletsApplicantUser.setDeptId(kv.getDeptId());
                        findAppletsApplicantUser.setOpenid(oldOpenid);
                        findAppletsApplicantUser.setAreatype(kv.getAreatype());
                        appletsApplicantUserService.insertAppletsApplicantUser(findAppletsApplicantUser);
                    }else{
                        oldAppletsApplicantUser.setUsertype(findAppletsApplicantUser.getUsertype());
                        oldAppletsApplicantUser.setName(findAppletsApplicantUser.getName());
                        oldAppletsApplicantUser.setGender(findAppletsApplicantUser.getGender());
                        oldAppletsApplicantUser.setBorntime(findAppletsApplicantUser.getBorntime());
                        oldAppletsApplicantUser.setCertificatestype(findAppletsApplicantUser.getCertificatestype());
                        oldAppletsApplicantUser.setCertificatesnumber(findAppletsApplicantUser.getCertificatesnumber());
                        oldAppletsApplicantUser.setCertificatesaddr(findAppletsApplicantUser.getCertificatesaddr());
                        oldAppletsApplicantUser.setCorporationname(findAppletsApplicantUser.getCorporationname());
                        oldAppletsApplicantUser.setMailbox(findAppletsApplicantUser.getMailbox());
                        appletsApplicantUserService.updateAppletsApplicantUser(oldAppletsApplicantUser);
                    }
                }
            });
        }
        appletsApplicantUserLogService.insertLong(appletsApplicantUser.getOpenid(),content);
        return toResult(rows);
    }
    //百度OCR
    @PostMapping("/idCardOcr")
    public Result idCardOcr(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String idCardImg = StringUtils.isHcNull(wechatView.getIdCardImg(),"");
        if("".equals(idCardImg)){
            return Result.cloud_602("idCardImg不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        BasicView basicView=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(openidView.getConfigId())),BasicView.class);
        FileInfoView fileInfoView=FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
        boolean isUpload= Base64Converter.generateFile(idCardImg,fileInfoView.getPathFileName());
        BdIdCardResult idCardInfo = new BdIdCardResult();
        if (isUpload){
             idCardInfo = BdOrcUtil.getIdCardInfo("front",fileInfoView.getPathFileName(),basicView.getBdocr().getAppid(),basicView.getBdocr().getAppkey(),basicView.getBdocr().getAppsecret());
        }else{
            return Result.cloud_602("图片解析失败!");
        }
        return Result.success(idCardInfo);
    }
    //冀时办人员信息获取
    @PostMapping("/getJiShiBanUser")
    public Result getJiShiBanUser(@RequestBody JiShiBanView jiShiBanView)
    {
        AppletsApplicantUser appletsApplicantUser = new AppletsApplicantUser();
        String accessLink = StringUtils.isHcNull(jiShiBanView.getAccessLink(),"");
        if("".equals(accessLink)){
            return Result.cloud_602("accessLink不能为空");
        }
        String rspStr = HttpUtils.sendGet(ComUtil.JISHIBAN_URL, "C-App-Id="+ComUtil.JISHIBAN_APPID+"&appPwd="+ComUtil.JISHIBAN_PWD+"&accessLink="+accessLink, Constants.UTF8);
        JSONObject reuslt = JSON.parseObject(rspStr);
        if (reuslt.containsKey("C-API-Status")){
            String code=String.valueOf(reuslt.get("C-API-Status"));
            if ("00".equals(code)){
                if (reuslt.containsKey("C-Response-Body")){
                    String body = StringUtils.isHcNull(String.valueOf(reuslt.get("C-Response-Body")),"");
                    if (!"".equals(body) && !"null".equals(body)){
                        InterfaceBackUser interfaceBackUser=JSON.parseObject(body,InterfaceBackUser.class);
                        if ("111".equals(interfaceBackUser.getCert_Type())){
                            appletsApplicantUser.setName(interfaceBackUser.getTruename());
                            appletsApplicantUser.setCertificatesnumber(interfaceBackUser.getIdcard());
                            appletsApplicantUser.setPhone(interfaceBackUser.getMobile());
                        }
                    }
                }
            }
        }
        return Result.success(appletsApplicantUser);
    }
    //获取人员列表
    @PostMapping("/getUserList")
    public Result getUserList(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        AppletsApplicantUser appletsApplicantUser = new AppletsApplicantUser();
        appletsApplicantUser.setOpenid(openid);
        List<AppletsApplicantUser> selectAppletsApplicantUserList=appletsApplicantUserService.selectAppletsApplicantUserList(appletsApplicantUser);
        List<AppletsApplicantUser> delList = new ArrayList<>();
        selectAppletsApplicantUserList.forEach(kv->{
              String  name = StringUtils.isHcNull(kv.getName(),"");
              if ("".equals(name)){
                  delList.add(kv);
              }
        });
        if (delList.size()>0){
            selectAppletsApplicantUserList.removeAll(delList);
        }
        return Result.success(selectAppletsApplicantUserList);
    }
    //根据ID获取人员信息
    @PostMapping("/getUserById")
    public Result getUserById(@RequestBody WechatView wechatView)
    {
        if(!StringUtils.isNotNull(wechatView.getApplicantId())){
            return Result.cloud_602("applicantId不能为空");
        }
        AppletsApplicantUser selectAppletsApplicantUserById=appletsApplicantUserService.selectAppletsApplicantUserById(wechatView.getApplicantId());
        return Result.success(selectAppletsApplicantUserById);
    }
    //获取类别
    @PostMapping("/category")
    public Result getCategory(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        //先判断分类
        Long configId=-1L;
        List<AppletsConfigMatterDetail> selectAppletsConfigMatterDetailList=appletsConfigMatterDetailService.selectAppletsConfigMatterDetailList(new AppletsConfigMatterDetail(openidView.getConfigId()));
        if(selectAppletsConfigMatterDetailList.size()>0){
            configId=openidView.getConfigId();
        }
        List<KvView> kvViewList= new ArrayList<KvView>();
        List<String> selectListCategoryByConfigId=appletsConfigMatterDetailService.selectListCategoryByConfigId(configId);
        List<SysDictData> selectDictDataByType=dictTypeService.selectDictDataByType(ComUtil.CONFIG_CATEGORY);
        selectDictDataByType.forEach(category->{
               if(selectListCategoryByConfigId.contains(category.getDictValue())){
                   KvView kvView = new KvView();
                   kvView.setKey(category.getDictValue());
                   kvView.setValue(category.getDictLabel());
                   kvViewList.add(kvView);
               }
        });
        return Result.success(kvViewList);
    }
    //获取用途
    @PostMapping("/purpose")
    public Result getPurpose(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        List<KvView> kvViewList= new ArrayList<KvView>();
        List<SysDictData> selectDictDataByType=dictTypeService.selectDictDataByType(ComUtil.CONFIG_PURPOSE);
        selectDictDataByType.forEach(purpose->{
                KvView kvView = new KvView();
                kvView.setKey(purpose.getDictValue());
                kvView.setValue(purpose.getDictLabel());
                kvViewList.add(kvView);
        });
        return Result.success(kvViewList);
    }
    //根据类别获取使用地
    @PostMapping("/place")
    public Result getPlace(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String category = StringUtils.isHcNull(wechatView.getCategory(),"");
        if("".equals(category)){
            return Result.cloud_602("category不能为空");
        }
        Map<String,String> placeState= new HashMap<String,String>();
        List<SysDictData> selectDictDataByType=dictTypeService.selectDictDataByType(ComUtil.CONFIG_PLACE);
        selectDictDataByType.forEach(plc->{
            placeState.put(plc.getDictValue(),plc.getStatus());
        });
        LinkedHashMap<String, List<PlaceView>> placeMap = new LinkedHashMap<>();
        List<SysCountry> selectSysCountryList=sysCountryService.selectSysCountryList(new SysCountry(category));
        List<PlaceView> hotlist= new ArrayList<PlaceView>();
        selectSysCountryList.forEach(kv->{
            if(!StringUtils.isNull(placeState.get(kv.getCountrynumber()))){
                PlaceView placeView = new PlaceView();
                placeView.setKey(kv.getCountrynumber());
                placeView.setValue_pinyin(kv.getCountrywhole());
                placeView.setCity_jp(kv.getCountryspelling());
                placeView.setValue(kv.getCountryname());
                String path = "/country/"+kv.getCountrypath()+".png";
                placeView.setPath(path);
                String idx=kv.getCountryinitials();
                List<PlaceView> placeViewList= new ArrayList<>();
                if(!StringUtils.isNull(placeMap.get(idx))) {
                    placeViewList=placeMap.get(idx);
                }
                if(!StringUtils.isNull(kv.getHost())){
                    if (kv.getHost() == 1L){
                        hotlist.add(placeView);
                    }
                }
                placeViewList.add(placeView);
                placeMap.put(idx,placeViewList);
            }
        });
        List<PlaceView2> placeView2List=new ArrayList<>();
        Iterator it = placeMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            PlaceView2 placeView2 = new PlaceView2();
            placeView2.setIdx(String.valueOf(entry.getKey()));
            placeView2.setCountries(placeMap.get(String.valueOf(entry.getKey())));
            placeView2List.add(placeView2);
        }
        WxPlaceView wxPlaceView = new WxPlaceView();
        wxPlaceView.setCountrieslist(placeView2List);
        wxPlaceView.setHotlist(hotlist);
        return Result.success(wxPlaceView);
    }
    //根据使用地获取语种
    @PostMapping("/language")
    public Result getLanguage(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String country = StringUtils.isHcNull(wechatView.getCountry(),"");
        if("".equals(country)){
            return Result.cloud_602("country不能为空");
        }
        List<SysCountryIanguages> selectSysCountryIanguagesList=sysCountryIanguagesService.selectSysCountryIanguagesList(new SysCountryIanguages(country));
        List<String> ianguagesList = new ArrayList<>();
        selectSysCountryIanguagesList.forEach(ci->{
            ianguagesList.add(ci.getIanguages());
        });
        List<KvView> kvViewList= new ArrayList<KvView>();
        List<SysDictData> selectDictDataByType=dictTypeService.selectDictDataByType(ComUtil.CONFIG_IANGUAGES);
        selectDictDataByType.forEach(ianguages->{
            if(ianguagesList.contains(ianguages.getDictValue())){
                KvView kvView = new KvView();
                kvView.setKey(ianguages.getDictValue());
                kvView.setValue(ianguages.getDictLabel());
                kvViewList.add(kvView);
            }
        });
        return Result.success(kvViewList);
    }
    //获取申办号
    @PostMapping("/getBusinessId")
    public Result getBusinessId(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String businessId=SerialNumberUtils.getSerialNumber(NumbereEnum.SYS_APPLETS_BID_NUMBER);
        BidDataView bidDataView = new BidDataView();
        bidDataView.setBusinessId(businessId);
        bidDataView.setOpenid(openid);
        redisCache.setCacheObject(ComUtil.getWechatBusinessKey(openid),bidDataView);
        return Result.success();
    }
    //基础数据缓存
    @PostMapping("/setInfo")
    public Result setInfo(@RequestBody BidDataView bidDataView)
    {
        String openid = StringUtils.isHcNull(bidDataView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        BidDataView bidDataView1 =redisCache.getCacheObject(ComUtil.getWechatBusinessKey(openid));
        String[] nullPropertyNames = BeanUtils.getNullPropertyNames(bidDataView);
        BeanUtils.copyProperties(bidDataView,bidDataView1,nullPropertyNames);
        redisCache.setCacheObject(ComUtil.getWechatBusinessKey(openid),bidDataView1);
        return Result.success();
    }


    //基础数据缓存-网站
    @PostMapping("/setWebInfo")
    public Result setWebInfo(@RequestBody BidWebDataView bidWebDataView)
    {
        String openid = StringUtils.isHcNull(bidWebDataView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        Map<String,String> categoryHt= new HashMap<String,String>();
        List<SysDictData> categoryList=dictTypeService.selectDictDataByType(ComUtil.CONFIG_CATEGORY);
        categoryList.forEach(kv->{
            categoryHt.put(kv.getDictValue(),kv.getDictLabel());
        });
        Map<String,String> purposeHt= new HashMap<String,String>();
        List<SysDictData> purposeList=dictTypeService.selectDictDataByType(ComUtil.CONFIG_PURPOSE);
        purposeList.forEach(kv->{
            purposeHt.put(kv.getDictValue(),kv.getDictLabel());
        });
        Map<String,String> placeHt= new HashMap<String,String>();
        List<SysDictData> placeList=dictTypeService.selectDictDataByType(ComUtil.CONFIG_PLACE);
        placeList.forEach(kv->{
            placeHt.put(kv.getDictValue(),kv.getDictLabel());
        });
        Map<String,String> ianguagesHt= new HashMap<String,String>();
        List<SysDictData> ianguagesList=dictTypeService.selectDictDataByType(ComUtil.CONFIG_IANGUAGES);
        ianguagesList.forEach(kv->{
            ianguagesHt.put(kv.getDictValue(),kv.getDictLabel());
        });
        String businessId=SerialNumberUtils.getSerialNumber(NumbereEnum.SYS_APPLETS_BID_NUMBER);
        BidDataView bidDataView = new BidDataView();
        bidDataView.setBusinessId(businessId);
        bidDataView.setOpenid(openid);
        CurrencyView category = new CurrencyView();
        category.setKey(bidWebDataView.getCategory());
        category.setValue(categoryHt.get(bidWebDataView.getCategory()));
        bidDataView.setCategory(category);
        CurrencyView purpose = new CurrencyView();
        purpose.setKey(bidWebDataView.getPurpose());
        purpose.setValue(purposeHt.get(bidWebDataView.getPurpose()));
        bidDataView.setPurpose(purpose);
        CurrencyView place = new CurrencyView();
        place.setKey(bidWebDataView.getPlace());
        place.setValue(placeHt.get(bidWebDataView.getPlace()));
        bidDataView.setPlace(place);
        CurrencyView language = new CurrencyView();
        language.setKey(bidWebDataView.getLanguage());
        language.setValue(ianguagesHt.get(bidWebDataView.getLanguage()));
        bidDataView.setLanguage(language);
        CurrencyView appointedNotary = new CurrencyView();
        appointedNotary.setKey("随机分配");
        appointedNotary.setValue("");
        bidDataView.setAppointedNotary(appointedNotary);
        MailView mail = new MailView();
        mail.setName("");
        mail.setPhone("");
        mail.setAddress("");
        mail.setDetailAddress("");
        bidDataView.setMail(mail);
        bidDataView.setUrgent("false");
        bidDataView.setAttestation("false");
        redisCache.setCacheObject(ComUtil.getWechatBusinessKey(openid),bidDataView);
        return Result.success();
    }


    //获取指定公证员
    @PostMapping("/getAppointedNotaryList")
    public Result getAppointedNotaryList(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String category = StringUtils.isHcNull(wechatView.getCategory(),"");
        if("".equals(category)){
            return Result.cloud_602("category不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        AppletsPublicParam specifyData=new AppletsPublicParam();
        specifyData.setDeptId(openidView.getDeptId());
        specifyData.setParamType(publicParamEnum.APPLETS_PUBLIC_PARAM_SPECIFY.getKey());
        specifyData.setCategory(category);
        List<AppletsPublicParam> specifyDataList=appletsPublicParamService.selectAppletsPublicParamList(specifyData);
        return Result.success(specifyDataList);
    }
    //获取公证事项
    @PostMapping("/matter")
    public Result getMatter(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String category = StringUtils.isHcNull(wechatView.getCategory(),"");
        if("".equals(category)){
            return Result.cloud_602("category不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        //先判断分类
        Long configId=-1L;
        List<AppletsConfigMatterDetail> selectAppletsConfigMatterDetailList=appletsConfigMatterDetailService.selectAppletsConfigMatterDetailList(new AppletsConfigMatterDetail(openidView.getConfigId()));
        if(selectAppletsConfigMatterDetailList.size()>0){
            configId=openidView.getConfigId();
        }
        //1.根据类别和configId获取事项编号列表并生成材料的map
            //获取所有事项的启用/禁用状态
            List<Map<String,String>> stateMap= appletsConfigMatterService.findMap(configId);
            Map<String,String> resState = ComUtil.mapListByMap(stateMap,"matter_number");
            //1.1遍历组装材料
            Map<String,String> clMap = new HashMap<String,String>();
            List<SysDictData> selectDictDataByType=dictTypeService.selectDictDataByType(ComUtil.CONFIG_MATERIAL);
            selectDictDataByType.forEach(clKv ->{
                clMap.put(clKv.getDictValue(),clKv.getDictLabel());
            });
            //1.2遍历数据
            List<String> matterList= new ArrayList<>();
            Map<String,List<CurrencyView>> stringListMap = new HashMap<String,List<CurrencyView>>();
            AppletsConfigMatterDetail appletsConfigMatterDetail = new AppletsConfigMatterDetail();
            appletsConfigMatterDetail.setConfigId(configId);
            appletsConfigMatterDetail.setMatterType("0");
            appletsConfigMatterDetail.setState("true");
            appletsConfigMatterDetail.setTypeNumber(category);
            List<AppletsConfigMatterDetail> appletsConfigMatterDetailList=appletsConfigMatterDetailService.selectAppletsConfigMatterDetailList(appletsConfigMatterDetail);
            appletsConfigMatterDetailList.forEach(matter->{
                   String matterNumber=matter.getMatterNumber();
                   if("true".equals(resState.get(matterNumber))){
                       stringListMap.put(matterNumber,new ArrayList<>());
                       matterList.add(matterNumber);
                   }
            });
            appletsConfigMatterDetail.setMatterType("1");
            appletsConfigMatterDetail.setTypeNumber(null);
            appletsConfigMatterDetail.setState(null);
            List<AppletsConfigMatterDetail> appletsConfigMatterDetailList2=appletsConfigMatterDetailService.selectAppletsConfigMatterDetailList(appletsConfigMatterDetail);
            appletsConfigMatterDetailList2.forEach(matter->{
                 String matterNumber=matter.getMatterNumber();
                 List<CurrencyView> materialList= new ArrayList<>();
                 if(!StringUtils.isNull(stringListMap.get(matterNumber))) {
                        materialList=stringListMap.get(matterNumber);
                        if(!StringUtils.isNull(clMap.get(matter.getTypeNumber()))) {
                             CurrencyView currencyView = new CurrencyView();
                             currencyView.setKey(matter.getTypeNumber());
                             currencyView.setValue(clMap.get(matter.getTypeNumber()));
                             materialList.add(currencyView);
                             stringListMap.put(matterNumber,materialList);
                        }
                 }
            });
        //2.根据最终事项 封装数据
        String[] matterNumbers=matterList.toArray(new String[matterList.size()]);
        List<SysMatter> selectSysMatterByMatterNumberList=sysMatterService.selectSysMatterByMatterNumberList(matterNumbers);
        Map<String,List<MatterView>> matterListMap = new HashMap<String,List<MatterView>>();
        selectSysMatterByMatterNumberList.forEach(kv->{
            String idx=kv.getClassification();
            MatterView matterView=new MatterView();
            matterView.setId(idx);
            matterView.setName(kv.getMatterName());
            matterView.setKey(kv.getMatterNumber());
            matterView.setDescription(kv.getRemarks());
            matterView.setName_image(kv.getThumbnail());
            matterView.setImages(kv.getRotation());
            matterView.setSimple_image(kv.getMattericon());
            matterView.setMaterial_labels(stringListMap.get(kv.getMatterNumber()));
            List<MatterView> matterViewList=new ArrayList<MatterView>();
            if(!StringUtils.isNull(matterListMap.get(idx))) {
                matterViewList=matterListMap.get(idx);
            }
            matterViewList.add(matterView);
            matterListMap.put(idx,matterViewList);
        });
        List<MatterDataView> matterDataViewList = new ArrayList<>();
        List<SysDictData> matterTypeList=dictTypeService.selectDictDataByType(ComUtil.CONFIG_MATTER_TYPE);
        matterTypeList.forEach(flKv ->{
            if(!StringUtils.isNull(matterListMap.get(flKv.getDictValue()))) {
                MatterDataView matterDataView= new MatterDataView();
                matterDataView.setId(flKv.getDictValue());
                matterDataView.setName(flKv.getDictLabel());
                String path = "/classificationImg/"+flKv.getDictValue()+".png";
                matterDataView.setCategory_image_url(path);
                matterDataView.setProducts(matterListMap.get(flKv.getDictValue()));
                matterDataViewList.add(matterDataView);
            }
        });
        return Result.success(matterDataViewList);
    }
    //事项信息缓存
    @PostMapping("/setMatter")
    public Result setMatter(@RequestBody WechatMatterView wechatMatterView)
    {
        String openid = StringUtils.isHcNull(wechatMatterView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        BidDataView bidDataView1 =redisCache.getCacheObject(ComUtil.getWechatBusinessKey(openid));
        bidDataView1.setMatter(wechatMatterView.getMatter());
        redisCache.setCacheObject(ComUtil.getWechatBusinessKey(openid),bidDataView1);
        return Result.success();
    }


    //获取事项对应的材料列表
    @PostMapping("/material")
    public Result getMaterial(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        //先判断分类
        Long configId=-1L;
        List<AppletsConfigMatterDetail> selectAppletsConfigMatterDetailList=appletsConfigMatterDetailService.selectAppletsConfigMatterDetailList(new AppletsConfigMatterDetail(openidView.getConfigId()));
        if(selectAppletsConfigMatterDetailList.size()>0){
            configId=openidView.getConfigId();
        }
        BidDataView bidDataView1 =redisCache.getCacheObject(ComUtil.getWechatBusinessKey(openid));
        List<MatterRedisView> matter=bidDataView1.getMatter();
        List<String> matterNumberList=new ArrayList<String>();
        matter.forEach(kv->{
            if(!matterNumberList.contains(kv.getKey())){
                matterNumberList.add(kv.getKey());
            }
        });
        if(matterNumberList.size() == 0 || StringUtils.isNull(matterNumberList)){
            return Result.cloud_602("未找到事项信息!");
        }
        Map<String,String> materialListMap = new HashMap<String,String>();
        for (String matterNumber:matterNumberList){
            AppletsConfigMatterDetail appletsConfigMatterDetail = new AppletsConfigMatterDetail();
            appletsConfigMatterDetail.setConfigId(configId);
            appletsConfigMatterDetail.setMatterNumber(matterNumber);
            appletsConfigMatterDetail.setMatterType("1");
            List<AppletsConfigMatterDetail> appletsConfigMatterDetailList=appletsConfigMatterDetailService.selectAppletsConfigMatterDetailList(appletsConfigMatterDetail);
            appletsConfigMatterDetailList.forEach(kv->{
                    String materialNumber=StringUtils.isHcNull(kv.getTypeNumber(),"");
                    String must=StringUtils.isHcNull(kv.getMust(),"");
                    if("".equals(must)){
                        must="false";
                    }
                    if(StringUtils.isNull(materialListMap.get(materialNumber))){
                           materialListMap.put(materialNumber,must);
                    }else{
                         if("false".equals(materialListMap.get(materialNumber))){
                             materialListMap.put(materialNumber,must);
                         }
                    }
            });
        }
        List<MaterialView> materialList =  new ArrayList<MaterialView>();
        List<SysDictData> matterTypeList=dictTypeService.selectDictDataByType(ComUtil.CONFIG_MATERIAL);
        matterTypeList.forEach(flKv ->{
            if(!StringUtils.isNull(materialListMap.get(flKv.getDictValue()))) {
                MaterialView materialView=new MaterialView();
                materialView.setDetailId(flKv.getDictValue());
                materialView.setIsMust(materialListMap.get(flKv.getDictValue()));
                materialView.setName(flKv.getDictLabel());
                materialList.add(materialView);
            }
        });
        materialList.sort(Comparator.comparing(MaterialView::getIsMust).reversed());
        return Result.success(materialList);
    }
    //材料信息缓存
    @PostMapping("/setMaterial")
    public Result setMaterial(@RequestBody WechatMaterialView wechatMaterialView)
    {
        String openid = StringUtils.isHcNull(wechatMaterialView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        MaterialView material=wechatMaterialView.getMaterial();
        material.getPathUrl().forEach(kv->{
            FileInfoView fileInfoView=FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
            boolean isUpload= Base64Converter.generateFile(kv.getPath(),fileInfoView.getPathFileName());
            if(isUpload){
                kv.setPath(fileInfoView.getFilePath());
                kv.setKey(fileInfoView.getFileName());
                kv.setType(fileInfoView.getFileType());
            }
        });
        BidDataView bidDataView1 =redisCache.getCacheObject(ComUtil.getWechatBusinessKey(openid));
        List<MaterialView> materialList=bidDataView1.getMaterial();
        materialList.add(material);
        bidDataView1.setMaterial(materialList);
        redisCache.setCacheObject(ComUtil.getWechatBusinessKey(openid),bidDataView1);
        return Result.success();
    }

    //材料信息缓存-网站
    @PostMapping("/setWebMaterial")
    public Result setWebMaterial(@RequestBody WebMaterialView webMaterialView)
    {
        String openid = StringUtils.isHcNull(webMaterialView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        List<MaterialView> materialList = new ArrayList<MaterialView>();
        List<MaterialWebRedisView> webMaterialList = webMaterialView.getMaterial();
        webMaterialList.forEach(kv->{
            MaterialView materialView = new MaterialView();
            materialView.setDetailId(kv.getDetailId());
            materialView.setName(kv.getName());
            List<KvView> pathUrl = new ArrayList<KvView>();
            KvView kvView = new KvView();
            kvView.setPath(kv.getPath());
            kvView.setType(kv.getType());
            pathUrl.add(kvView);
            materialView.setPathUrl(pathUrl);
            materialList.add(materialView);
        });
        BidDataView bidDataView1 =redisCache.getCacheObject(ComUtil.getWechatBusinessKey(openid));
        bidDataView1.setMaterial(materialList);
        redisCache.setCacheObject(ComUtil.getWechatBusinessKey(openid),bidDataView1);
        return Result.success();
    }

    //材料信息缓存-公众号
    @PostMapping("/setGzhMaterial")
    public Result setGzhMaterial(@RequestBody WebMaterialView webMaterialView)
    {
        String openid = StringUtils.isHcNull(webMaterialView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        BidDataView bidDataView1 =redisCache.getCacheObject(ComUtil.getWechatBusinessKey(openid));
        List<MaterialView> materialList = bidDataView1.getMaterial();
        List<MaterialWebRedisView> webMaterialList = webMaterialView.getMaterial();
        webMaterialList.forEach(kv->{
            MaterialView materialView = new MaterialView();
            materialView.setDetailId(kv.getDetailId());
            materialView.setName(kv.getName());
            List<KvView> pathUrl = new ArrayList<KvView>();
            KvView kvView = new KvView();
            kvView.setPath(kv.getPath());
            kvView.setType(kv.getType());
            pathUrl.add(kvView);
            materialView.setPathUrl(pathUrl);
            materialList.add(materialView);
        });
        bidDataView1.setMaterial(materialList);
        redisCache.setCacheObject(ComUtil.getWechatBusinessKey(openid),bidDataView1);
        return Result.success();
    }

    //数据入库
    @PostMapping("/submit")
    public Result submit(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        BidDataView bidDataView =redisCache.getCacheObject(ComUtil.getWechatBusinessKey(openid));
        if(StringUtils.isNull(bidDataView)){
            return Result.error();
        }
        if ("".equals(StringUtils.isHcNull(openidView.getRealName(),"")) && "2".equals(openidView.getAreatype())){
            AtomicReference<String> sqrName = new AtomicReference<>("");
            AppletsApplicantUser appletsApplicantUser = new AppletsApplicantUser();
            appletsApplicantUser.setOpenid(openid);
            List<AppletsApplicantUser> selectAppletsApplicantUserList=appletsApplicantUserService.selectAppletsApplicantUserList(appletsApplicantUser);
            List<AppletsApplicantUser> delList = new ArrayList<>();
            selectAppletsApplicantUserList.forEach(kv->{
                String  name = StringUtils.isHcNull(kv.getName(),"");
                if (!"".equals(name)){
                    sqrName.set(name);
                }
            });
            openidView.setRealName(sqrName.get());
        }
        //短信  如未选  随机分配
        Map<String,String> resState = JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigStateMap().get(openidView.getConfigId())),Map.class);
        String  message =  resState.get(BasicParamEnum.SYS_APPLETS_BASIC_MESSAGE.getKey()) == null?"false":resState.get(BasicParamEnum.SYS_APPLETS_BASIC_MESSAGE.getKey());
        if ("true".equals(message)){
            String  phone = StringUtils.isHcNull(bidDataView.getAppointedNotary().getValue(),"");
            if ("".equals(phone)){
                AppletsPublicParam appletsPublicParam=new AppletsPublicParam();
                appletsPublicParam.setDeptId(openidView.getDeptId());
                appletsPublicParam.setParamType(publicParamEnum.APPLETS_PUBLIC_PARAM_SPECIFY.getKey());
                appletsPublicParam.setCategory(bidDataView.getCategory().getKey());
                List<AppletsPublicParam> specifyDataList=appletsPublicParamService.selectAppletsPublicParamList(appletsPublicParam);
                if (!StringUtils.isEmpty(specifyDataList)){
                    Random random = new Random();
                    int n = random.nextInt(specifyDataList.size());
                    AppletsPublicParam publicParam = specifyDataList.get(n);
                    if (StringUtils.isNotNull(publicParam) ){
                        CurrencyView randomNotary = new CurrencyView();
                        randomNotary.setKey(publicParam.getUsername());
                        randomNotary.setValue(publicParam.getPhone());
                        bidDataView.setAppointedNotary(randomNotary);
                    }
                }
            }
        }
        Long businessid=appletsBusinessService.insertAppletsBusinessData(openidView,bidDataView);//入库获取主键id
        //遍历事项 入库事项表 当事人表  费用表
        List<MatterRedisView> newMatterList = new ArrayList<MatterRedisView>();
        List<MatterRedisView> matterList=bidDataView.getMatter();
        //先判断是否是文本相符的事项，是则添加事项
        if(ComUtil.isTextMatch(bidDataView.getPlace().getKey())){
            newMatterList.clear();
            for(MatterRedisView matterRedisView : matterList) {
                MatterRedisView matterRedisView1 = JSON.parseObject(JSON.toJSONString(matterRedisView),MatterRedisView.class);
                newMatterList.add(matterRedisView1);
                MatterRedisView matterRedisView2 = JSON.parseObject(JSON.toJSONString(matterRedisView),MatterRedisView.class);
                matterRedisView2.setKey(ComUtil.CONFIG_TEXT_MATCH_MATTER_NUMBER);
                matterRedisView2.setValue("文本相符");
                newMatterList.add(matterRedisView2);
            }
        }else{
            newMatterList=matterList;
        }
        //先判断分类
        Long configId=-1L;
        List<AppletsConfigMatterDetail> selectAppletsConfigMatterDetailList=appletsConfigMatterDetailService.selectAppletsConfigMatterDetailList(new AppletsConfigMatterDetail(openidView.getConfigId()));
        if(selectAppletsConfigMatterDetailList.size()>0){
            configId=openidView.getConfigId();
        }
        Long findConfigId=configId;
        //1.1遍历组装材料
        Map<String,String> fyMap = new HashMap<String,String>();
        List<SysDictData> selectDictDataByType=dictTypeService.selectDictDataByType(ComUtil.CONFIG_CHARGE);
        selectDictDataByType.forEach(clKv ->{
            fyMap.put(clKv.getDictValue(),clKv.getDictLabel());
        });
        //入库
        newMatterList.forEach(metter->{
            //0 公证事项
            AppletsBusinessMatter appletsBusinessMatter = new AppletsBusinessMatter();
            appletsBusinessMatter.setConfigId(openidView.getConfigId());
            appletsBusinessMatter.setDeptId(openidView.getDeptId());
            appletsBusinessMatter.setBusinessid(businessid);
            appletsBusinessMatter.setMatter(metter.getKey());
            appletsBusinessMatter.setMattername(metter.getValue());
            appletsBusinessMatter.setStepper(metter.getStepper());
            appletsBusinessMatter.setTranslate(metter.getTranslate());
            List<String> partyList = new ArrayList<String>();
            List<AppletsApplicantUser> peopleList=metter.getPeopleList();
            peopleList.forEach(pkv->{
                partyList.add(pkv.getName());
            });
            appletsBusinessMatter.setParty(StringUtils.join(partyList.toArray(),","));
            appletsBusinessMatterService.insertAppletsBusinessMatter(appletsBusinessMatter);
            peopleList.forEach(pkv->{
                AppletsBusinessMatterApplicant appletsBusinessMatterApplicant = new AppletsBusinessMatterApplicant();
                appletsBusinessMatterApplicant.setConfigId(openidView.getConfigId());
                appletsBusinessMatterApplicant.setDeptId(openidView.getDeptId());
                appletsBusinessMatterApplicant.setBusinessid(businessid);
                appletsBusinessMatterApplicant.setMatterid(appletsBusinessMatter.getId());
                appletsBusinessMatterApplicant.setApplicantid(pkv.getId());
                appletsBusinessMatterApplicantService.insertAppletsBusinessMatterApplicant(appletsBusinessMatterApplicant);
            });
            //以下为费用计算
            AppletsConfigMatterDetail appletsConfigMatterDetail = new AppletsConfigMatterDetail();
            appletsConfigMatterDetail.setConfigId(findConfigId);
            appletsConfigMatterDetail.setMatterType("2");
            appletsConfigMatterDetail.setMatterNumber(metter.getKey());
            List<AppletsConfigMatterDetail> appletsConfigMatterDetailList=appletsConfigMatterDetailService.selectAppletsConfigMatterDetailList(appletsConfigMatterDetail);
            if (appletsConfigMatterDetailList.size()>0){
                appletsConfigMatterDetailList.forEach(fykv->{
                    AppletsBusinessCost appletsBusinessCost = new AppletsBusinessCost();
                    appletsBusinessCost.setConfigId(openidView.getConfigId());
                    appletsBusinessCost.setDeptId(openidView.getDeptId());
                    appletsBusinessCost.setBusinessid(businessid);
                    appletsBusinessCost.setMatterid(appletsBusinessMatter.getId());
                    appletsBusinessCost.setCost(fykv.getTypeNumber());
                    appletsBusinessCost.setCostname(fyMap.get(fykv.getTypeNumber()));
                    appletsBusinessCost.setTotalmoney(new BigDecimal(fykv.getMoney()));
                    appletsBusinessCost.setPaidmoney(new BigDecimal("0"));
                    appletsBusinessCostService.insertAppletsBusinessCost(appletsBusinessCost);
                });
            }else{
                AppletsBusinessCost appletsBusinessCost = new AppletsBusinessCost();
                appletsBusinessCost.setConfigId(openidView.getConfigId());
                appletsBusinessCost.setDeptId(openidView.getDeptId());
                appletsBusinessCost.setBusinessid(businessid);
                appletsBusinessCost.setMatterid(appletsBusinessMatter.getId());
                appletsBusinessCost.setCost(ComUtil.CONFIG_MATTER_NOTARIZATION_FEE);
                appletsBusinessCost.setCostname("公证费");
                appletsBusinessCost.setTotalmoney(new BigDecimal("0"));
                appletsBusinessCost.setPaidmoney(new BigDecimal("0"));
                appletsBusinessCostService.insertAppletsBusinessCost(appletsBusinessCost);
            }
        });
        //材料入库
        List<MaterialView> materialList =bidDataView.getMaterial();
        materialList.forEach(mkv->{
            List<KvView> pathUrl=mkv.getPathUrl();
            pathUrl.forEach(urlkv->{
                AppletsBusinessMaterial appletsBusinessMaterial = new AppletsBusinessMaterial();
                appletsBusinessMaterial.setConfigId(openidView.getConfigId());
                appletsBusinessMaterial.setDeptId(openidView.getDeptId());
                appletsBusinessMaterial.setBusinessid(businessid);
                appletsBusinessMaterial.setMaterial(mkv.getDetailId());
                appletsBusinessMaterial.setMaterialname(mkv.getName());
                appletsBusinessMaterial.setMaterialpath(urlkv.getPath());
                appletsBusinessMaterial.setMaterialtype(urlkv.getType());
                appletsBusinessMaterialService.insertAppletsBusinessMaterial(appletsBusinessMaterial);

            });
        });
        appletsBusinessService.updateCostAndMatter(businessid);
        redisCache.deleteObject(ComUtil.getWechatBusinessKey(openid));
        //短信通知公证员
        if ("true".equals(message)){
            String ly = "";
            if ("2".equals(openidView.getAreatype())) {
                ly = "网站";
            }else if("1".equals(openidView.getAreatype())){
                ly = "公众号";
            }else{
                ly = "小程序";
            }
            String  phone = StringUtils.isHcNull(bidDataView.getAppointedNotary().getValue(),"");
            if (!"".equals(phone)){
                List<String> phonelist = new ArrayList<String>();
                phonelist.add("+86"+phone);
                wxSendTplMessageService.sendAddOrder(phonelist, openidView.getConfigId(),"1",openidView.getRealName(),ly,bidDataView.getBusinessId());
            }else{
                AppletsPublicParam specifyData=new AppletsPublicParam();
                specifyData.setDeptId(openidView.getDeptId());
                specifyData.setParamType(publicParamEnum.APPLETS_PUBLIC_PARAM_NOTIFICATIONPHONE.getKey());
                List<AppletsPublicParam> specifyDataList=appletsPublicParamService.selectAppletsPublicParamList(specifyData);
                if (!StringUtils.isEmpty(specifyDataList) ){
                    AppletsPublicParam publicParam = specifyDataList.get(0);
                    if (!"".equals(StringUtils.isHcNull(publicParam.getPhone(),""))){
                        List<String> phonelist = new ArrayList<String>();
                        String[] phoneArr= publicParam.getPhone().split(",");
                        for (String sPhone : phoneArr) {
                            phonelist.add("+86"+sPhone);
                        }
                        wxSendTplMessageService.sendAddOrder(phonelist, openidView.getConfigId(),"1",openidView.getRealName(),ly,bidDataView.getBusinessId());
                    }
                }
            }
        }
        appletsApplicantUserLogService.insertLong(openid,"在平台完成案件申请，申办号为【"+bidDataView.getBusinessId()+"】。");
        Result ajax = Result.success();
        ajax.put("businessId",bidDataView.getBusinessId());
        ajax.put("datatime", DateUtils.getTime());
        return ajax;
    }

    //订单列表
    @PostMapping("/order")
    public Result order(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        Map<String,String> iconMatterHt = new HashMap();
        List<SysMatter>  sysMatterList = sysMatterService.selectSysMatterList(null);
        sysMatterList.forEach(kv->{
            iconMatterHt.put(kv.getMatterNumber(),kv.getMattericon());
        });
        //公众号和小程序公用订单
        List<String> openidList = new ArrayList<>();
        AppletsWechatUser appletsWechatUser = appletsWechatUserService.selectAppletsWechatUserById(openid);
        String unionid = "";
        if(StringUtils.isNotNull(appletsWechatUser)){
            unionid = StringUtils.isHcNull(appletsWechatUser.getUnionid(),"");
        }
        if (!"".equals(unionid)){
            AppletsWechatUser oldAppletsWechatUserData = new AppletsWechatUser();
            oldAppletsWechatUserData.setUnionid(unionid);
            List<AppletsWechatUser>  oldAppletsWechatUserList = appletsWechatUserService.selectAppletsWechatUserList(oldAppletsWechatUserData);
            oldAppletsWechatUserList.forEach(kv->{
                openidList.add(kv.getOpenid());
            });
        }
        List<OrderPublicAppletsBusiness> orderList = new ArrayList<>();
        List<AppletsBusiness>  appletsBusinessList = null;
        if (openidList.size() >0){
            appletsBusinessList = appletsBusinessService.selectAppletsBusinessOrderList(openidList.toArray(new String[openidList.size()]));
        }else{
            AppletsBusiness appletsBusiness = new AppletsBusiness();
            appletsBusiness.setConfigId(openidView.getConfigId());
            appletsBusiness.setOpenid(openid);
            appletsBusinessList = appletsBusinessService.selectAppletsBusinessList(appletsBusiness);
        }
        appletsBusinessList.forEach(kv->{
            OrderPublicAppletsBusiness orderPublicAppletsBusiness = new OrderPublicAppletsBusiness();
            BeanUtils.copyProperties(kv,orderPublicAppletsBusiness);
            List<AppletsBusinessMatter> appletsBusinessMatterList = new ArrayList<>();
            List<AppletsBusinessMatter> appletsBusinessMatter = appletsBusinessMatterService.selectAppletsBusinessMatterList(new AppletsBusinessMatter(kv.getId()));
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //24小时制
            for (AppletsBusinessMatter dto:appletsBusinessMatter
            ) {
                String date = df.format(dto.getOperatortime());
                dto.setOperatortimeStr(date);
            }
            appletsBusinessMatter.forEach(matter->{
                matter.setMattericon(iconMatterHt.get(matter.getMatter()));
                List<AppletsBusinessCost> appletsBusinessCostList=appletsBusinessCostService.selectAppletsBusinessCostList(new AppletsBusinessCost(kv.getId(),matter.getId()));
                BigDecimal totalAmount = new BigDecimal(0);
                for (int i = 0; i < appletsBusinessCostList.size() ; i++) {
                    totalAmount=totalAmount.add(appletsBusinessCostList.get(i).getTotalmoney());
                }
                matter.setNotarizationFee(totalAmount);
                appletsBusinessMatterList.add(matter);
            });
            orderPublicAppletsBusiness.setAppletsBusinessMatter(appletsBusinessMatterList);
            orderList.add(orderPublicAppletsBusiness);
        });
        return Result.success(orderList);
    }

    //订单列表-详情
    @PostMapping("/info")
    public Result info(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        Long businessId = wechatView.getBusinessId();
        if(StringUtils.isNull(businessId)){
            return Result.cloud_602("businessId不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        Map<String,String> iconMatterHt = new HashMap();
        List<SysMatter>  sysMatterList = sysMatterService.selectSysMatterList(null);
        sysMatterList.forEach(kv->{
            iconMatterHt.put(kv.getMatterNumber(),kv.getMattericon());
        });
        OrderPublicAppletsBusiness orderPublicAppletsBusiness = new OrderPublicAppletsBusiness();
        AppletsBusiness appletsBusiness = appletsBusinessService.selectAppletsBusinessById(businessId);
        BeanUtils.copyProperties(appletsBusiness,orderPublicAppletsBusiness);
        List<AppletsBusinessMatter> appletsBusinessMatterList = new ArrayList<>();
        List<AppletsBusinessMatter> appletsBusinessMatter = appletsBusinessMatterService.selectAppletsBusinessMatterList(new AppletsBusinessMatter(businessId));
        appletsBusinessMatter.forEach(matter->{
            matter.setMattericon(iconMatterHt.get(matter.getMatter()));
            List<AppletsBusinessCost> appletsBusinessCostList=appletsBusinessCostService.selectAppletsBusinessCostList(new AppletsBusinessCost(businessId,matter.getId()));
            BigDecimal totalAmount = new BigDecimal(0);
            for (int i = 0; i < appletsBusinessCostList.size() ; i++) {
                totalAmount=totalAmount.add(appletsBusinessCostList.get(i).getTotalmoney());
            }
            matter.setNotarizationFee(totalAmount);
            List<AppletsBusinessMatterApplicant> appletsBusinessMatterApplicantList = appletsBusinessMatterApplicantService.selectAppletsBusinessMatterApplicantList(new AppletsBusinessMatterApplicant(businessId,matter.getId()));
            List<Long> applicantIdList=new ArrayList<>();
            appletsBusinessMatterApplicantList.forEach(kv->{
                if(!applicantIdList.contains(kv.getApplicantid())){
                    applicantIdList.add(kv.getApplicantid());
                }
            });
            Long[] ids=applicantIdList.toArray(new Long[applicantIdList.size()]);
            List<AppletsApplicantUser> appletsApplicantUserList=appletsApplicantUserService.selectAppletsApplicantUserByIdList(ids);
            matter.setAppletsApplicantUserList(appletsApplicantUserList);
            appletsBusinessMatterList.add(matter);
        });
        orderPublicAppletsBusiness.setAppletsBusinessMatter(appletsBusinessMatterList);
        List<AppletsBusinessMaterial> appletsBusinessMaterial=appletsBusinessMaterialService.selectAppletsBusinessMaterialList(new AppletsBusinessMaterial(businessId));
        orderPublicAppletsBusiness.setAppletsBusinessMaterial(appletsBusinessMaterial);

        List<CurrencyView> currencyViewList = new ArrayList<>();
        List<Map<String,BigDecimal>> moneyMap= appletsBusinessCostService.findCostByMoneyMap(businessId);
        Map<String,String> moneyHt = ComUtil.mapListByBigDecimalMap(moneyMap,"cost");
        List<SysDictData> selectDictDataByType=dictTypeService.selectDictDataByType(ComUtil.CONFIG_CHARGE);
        selectDictDataByType.forEach(fyKv ->{
            CurrencyView currencyView = new CurrencyView();
            if(!StringUtils.isNull(moneyHt.get(fyKv.getDictValue()))) {
                currencyView.setKey(fyKv.getDictLabel());
                currencyView.setValue(moneyHt.get(fyKv.getDictValue()));
                currencyViewList.add(currencyView);
            }
        });
        orderPublicAppletsBusiness.setCostList(currencyViewList);
        return Result.success(orderPublicAppletsBusiness);
    }

    //订单列表-补材料
    @PostMapping("/repairMaterial")
    public Result repairMaterial(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        Long businessId = wechatView.getBusinessId();
        if(StringUtils.isNull(businessId)){
            return Result.cloud_602("businessId不能为空");
        }
        OrderPublicAppletsBusinessMaterial orderPublicAppletsBusinessMaterial = new OrderPublicAppletsBusinessMaterial();
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        AppletsBusiness appletsBusiness = appletsBusinessService.selectAppletsBusinessById(businessId);
        BeanUtils.copyProperties(appletsBusiness,orderPublicAppletsBusinessMaterial);
        List<AppletsBusinessMaterial> appletsBusinessMaterial=appletsBusinessMaterialService.selectAppletsBusinessMaterialList(new AppletsBusinessMaterial(businessId));
        orderPublicAppletsBusinessMaterial.setAppletsBusinessMaterial(appletsBusinessMaterial);
        BidDataView bidDataView = new BidDataView();
        bidDataView.setId(businessId);
        bidDataView.setOpenid(openid);
        bidDataView.setBusinessId(appletsBusiness.getBusinessid());
        redisCache.setCacheObject(ComUtil.getWechatBusinessKey(openid),bidDataView);
        return Result.success(orderPublicAppletsBusinessMaterial);
    }


    //数据入库-补材料
    @PostMapping("/repairMaterialSave")
    public Result repairMaterialSave(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        Long businessId = wechatView.getBusinessId();
        if(StringUtils.isNull(businessId)){
            return Result.cloud_602("businessId不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        BidDataView bidDataView =redisCache.getCacheObject(ComUtil.getWechatBusinessKey(openid));
        if(StringUtils.isNull(bidDataView)){
            return Result.error();
        }
        AppletsBusiness appletsBusiness = appletsBusinessService.selectAppletsBusinessById(businessId);
        //如果之前库里状态为补材料就进行处理
        if ("0".equals(appletsBusiness.getState())){
            appletsBusiness.setState("1");
            appletsBusinessService.updateAppletsBusiness(appletsBusiness);
        }
        //材料入库
        List<MaterialView> materialList =bidDataView.getMaterial();
        materialList.forEach(mkv->{
            List<KvView> pathUrl=mkv.getPathUrl();
            pathUrl.forEach(urlkv->{
                AppletsBusinessMaterial appletsBusinessMaterial = new AppletsBusinessMaterial();
                appletsBusinessMaterial.setConfigId(openidView.getConfigId());
                appletsBusinessMaterial.setDeptId(openidView.getDeptId());
                appletsBusinessMaterial.setBusinessid(bidDataView.getId());
                appletsBusinessMaterial.setMaterial(mkv.getDetailId());
                appletsBusinessMaterial.setMaterialname(mkv.getName());
                appletsBusinessMaterial.setMaterialpath(urlkv.getPath());
                appletsBusinessMaterial.setMaterialtype(urlkv.getType());
                appletsBusinessMaterialService.insertAppletsBusinessMaterial(appletsBusinessMaterial);

            });
        });
        redisCache.deleteObject(ComUtil.getWechatBusinessKey(openid));
        appletsApplicantUserLogService.insertLong(openid,"在小程序进行了补材料操作，申办号为【"+bidDataView.getBusinessId()+"】。");
        Result ajax = Result.success();
        ajax.put("businessId",bidDataView.getBusinessId());
        ajax.put("datatime", DateUtils.getTime());
        return ajax;
    }


    //撤销申请
    @PostMapping("/revokeInfo")
    public Result revokeInfo(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        Long businessId = wechatView.getBusinessId();
        if(StringUtils.isNull(businessId)){
            return Result.cloud_602("businessId不能为空");
        }
        AppletsBusiness appletsBusiness = appletsBusinessService.selectAppletsBusinessById(businessId);
        appletsBusiness.setState("99");
        appletsApplicantUserLogService.insertLong(openid,"在小程序进行了撤销案件操作，申办号为【"+appletsBusiness.getBusinessid()+"】。");
        return toResult(appletsBusinessService.updateAppletsBusiness(appletsBusiness));
    }

    //验证房间号是否存在
    @PostMapping("/getIsRoomId")
    public Result getIsRoomId(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String customroomid=StringUtils.isHcNull(wechatView.getCustomroomid(),"");
        if("".equals(customroomid)){
            return Result.cloud_602("房间号不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        List<AppletsBusinessVideo> appletsBusinessVideoList=appletsBusinessVideoService.selectAppletsBusinessVideoList(new AppletsBusinessVideo(openidView.getConfigId(),customroomid,"0"));
        if (StringUtils.isEmpty(appletsBusinessVideoList) ){
            return Result.cloud_602("房间号不存在");
        }
        return Result.success();
    }
    //进入房间号进行活体
    @PostMapping("/bizToken")
    public Result bizToken(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(openidView.getConfigId())),BasicView.class);
        CheckView checkView=basicView.getLivingthing();
        if (StringUtils.isNull(checkView)){
            return Result.cloud_602("活体检测未配置!");
        }
        AppletsApplicantUser appletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
        String biztoken=DetectAuthUtil.getVideoResult(checkView.getSecretId(),checkView.getSecretKey(),checkView.getRuleId(),appletsApplicantUser.getName(),appletsApplicantUser.getCertificatesnumber());
        if("".equals(StringUtils.isHcNull(biztoken,""))){
            return Result.cloud_602("活体检测参数错误!");
        }
        DetectAuthView view=JSON.parseObject(biztoken, DetectAuthView.class);
        return Result.success(view);
    }
    //进入房间号进行活体
    @PostMapping("/sendCallback")
    public Result sendCallback(@RequestBody WechatView wechatView) throws  Exception
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        String customroomid=StringUtils.isHcNull(wechatView.getCustomroomid(),"");
        if("".equals(customroomid)){
            return Result.cloud_602("房间号不能为空");
        }
        Map<String,String> resState = JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigStateMap().get(openidView.getConfigId())),Map.class);
        String isliving=resState.get(BasicParamEnum.SYS_APPLETS_BASIC_LIVINGTHING.getKey()) == null?"false":resState.get(BasicParamEnum.SYS_APPLETS_BASIC_LIVINGTHING.getKey());
        if("true".equals(isliving)){
            String biztoken = StringUtils.isHcNull(wechatView.getBiztoken(),"");
            if("".equals(biztoken)){
                return Result.cloud_602("biztoken不能为空,请先进行活体!");
            }
        }
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(openidView.getConfigId())),BasicView.class);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(openidView.getConfigId())),AppletsConfig.class);
        AppletsApplicantUser appletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
        List<AppletsBusinessVideo> appletsBusinessVideoList=appletsBusinessVideoService.selectAppletsBusinessVideoList(new AppletsBusinessVideo(openidView.getConfigId(),customroomid,"0"));
        if (StringUtils.isEmpty(appletsBusinessVideoList) ){
            return Result.cloud_602("房间已关闭!");
        }
        AppletsBusinessVideo businessVideo=appletsBusinessVideoList.get(0);
        WxVideoCallView wxVideoCallView=new WxVideoCallView(basicView.getRemotevideo().getAppid(),basicView.getRemotevideo().getKey(),String.valueOf(appletsApplicantUser.getId()),appletsApplicantUser.getName(),businessVideo.getRoomid(),businessVideo.getCustomroomid());
        wxVideoCallView.setBusinessId(businessVideo.getBusinessid());
        wxVideoCallView.setVideoId(businessVideo.getId());
        Long sid=0L;
        List<AppletsBusinessVideoUser> appletsBusinessVideoUserList=appletsBusinessVideoUserService.selectAppletsBusinessVideoUserList(new AppletsBusinessVideoUser(businessVideo.getId(),openid,"applets"));
        boolean isLiving=false;
        if (StringUtils.isEmpty(appletsBusinessVideoUserList) ){
            AppletsBusinessVideoUser appletsBusinessVideoUser = new AppletsBusinessVideoUser();
            appletsBusinessVideoUser.setConfigId(openidView.getConfigId());
            appletsBusinessVideoUser.setDeptId(openidView.getDeptId());
            appletsBusinessVideoUser.setVideoid(businessVideo.getId());
            appletsBusinessVideoUser.setOpenid(openid);
            appletsBusinessVideoUser.setSigntype("applets");
            appletsBusinessVideoUser.setIsliving("-1");
            appletsBusinessVideoUser.setSignuserid(appletsApplicantUser.getId());
            appletsBusinessVideoUser.setSignusername(appletsApplicantUser.getName());
            FileInfoView fileInfoView= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
            CenerateSignImage.getVenerateSign(appletsApplicantUser.getName(),fileInfoView.getPathFileName());
            appletsBusinessVideoUser.setSignimg(fileInfoView.getFilePath());
            int userrow=appletsBusinessVideoUserService.insertAppletsBusinessVideoUser(appletsBusinessVideoUser);
            if (userrow > 0){
                isLiving=true;
                sid=appletsBusinessVideoUser.getId();
            }
        }else{
            sid=appletsBusinessVideoUserList.get(0).getId();
            if ("-1".equals(appletsBusinessVideoUserList.get(0).getIsliving())){
                isLiving=true;
            }else{
                isLiving=false;
            }
        }
        wxVideoCallView.setSid(sid);
        if(!redisCache.isCacheKey(ComUtil.getWechatVideoRoomCacheKey(sid.toString()))){
            WebSocketUser webSocketUser = new WebSocketUser(sid.toString(),"applets",wxVideoCallView.getRoomId(),sid.toString().toString(),appletsApplicantUser.getName());
            redisCache.setCacheObject(ComUtil.getWechatVideoRoomCacheKey(sid.toString()),webSocketUser, 4, TimeUnit.HOURS);//缓存用户和房间号
        }
        //判断是否开启过视频录制
        String  requestid=StringUtils.isHcNull(businessVideo.getRequestid(),"");
        if ("".equals(requestid)){//开启
            String StreamId= IdUtils.simpleUUID();
            requestid= WxTencentCloudUtil.hladd(basicView.getRemotevideo().getSecretId(),basicView.getRemotevideo().getSecretKey(),basicView.getRemotevideo().getAppid(),wxVideoCallView.getRoomId(),StreamId);
            businessVideo.setRequestid(requestid);
            businessVideo.setRecordingid(StreamId);
            appletsBusinessVideoService.updateAppletsBusinessVideo(businessVideo);
        }

        //生成活体报告
        if("true".equals(isliving)){
            if (isLiving){
                String biztoken = StringUtils.isHcNull(wechatView.getBiztoken(),"");
                CheckView checkView=basicView.getLivingthing();
                wxAsyncService.getDetectVideoAuthInfo("video",openidView.getConfigId(),openidView.getDeptId(),biztoken,checkView,appletsConfig.getName(),appletsApplicantUser,wxVideoCallView);
            }
        }
        appletsApplicantUserLogService.insertLong(openid,"进入房间，申办号为【"+businessVideo.getBusinessid()+"】,房间号为："+wxVideoCallView.getRoomId());
        return Result.success(wxVideoCallView);
    }
    //判断用户是否在契约锁认证过
    @PostMapping("/getIsQysAuth")
    public Result getIsAuth(@RequestBody WechatView wechatView) throws  Exception
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(openidView.getConfigId())),BasicView.class);
        QysView qysView=basicView.getQys();
        if (StringUtils.isNull(qysView)){
            return Result.cloud_602("契约锁未配置!");
        }
        SdkClient client = new SdkClient(qysView.getUrl(), qysView.getAccesskey(), qysView.getAccessSecret());
        AppletsApplicantUser appletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
        QysUser qysUserAuth= new QysUser();
        qysUserAuth.setName(appletsApplicantUser.getName());
        qysUserAuth.setCertificatesnumber(appletsApplicantUser.getCertificatesnumber());
        if (!"".equals(StringUtils.isHcNull(appletsApplicantUser.getPhone(),""))){
            qysUserAuth.setType("1");
        }else{
            qysUserAuth.setType("2");
        }
        qysUserAuth.setPhone(appletsApplicantUser.getPhone());
        qysUserAuth.setMailbox(appletsApplicantUser.getMailbox());
        boolean flag=SendByCodeSetting.getIsAuth(client,qysUserAuth);
        String msg="SUCCESS";
        if(!flag){
            msg= SendByCodeSetting.getUserKey(client,qysUserAuth);
        }
        return Result.success("操作成功",msg);
    }
    //查询未签署的文书
    @PostMapping("/getQysKey")
    public Result getQysKey(@RequestBody WechatView wechatView) throws  Exception
    {
        String msg="";
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String videoId = StringUtils.isHcNull(wechatView.getVideoId(),"");
        if("".equals(videoId)){
            return Result.cloud_602("videoId不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        AppletsApplicantUser appletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(openid);
        //先查询用户所有待签署文书
        AppletsBusinessVideoSign appletsBusinessVideoSign = new AppletsBusinessVideoSign();
        appletsBusinessVideoSign.setVideoid(Long.valueOf(videoId));
        appletsBusinessVideoSign.setState("0");
        appletsBusinessVideoSign.setConfigId(openidView.getConfigId());
        List<AppletsBusinessVideoSign>   appletsBusinessVideoSignList = appletsBusinessVideoSignService.selectAppletsBusinessVideoSignList(appletsBusinessVideoSign);
        if (StringUtils.isEmpty(appletsBusinessVideoSignList) ){
            return Result.cloud_602("没有待签署的文书!");
        }
        List<String> uuidList = new ArrayList<>();
        String contratid="";
        for (AppletsBusinessVideoSign kv : appletsBusinessVideoSignList) {
            if(!"-1".equals(kv.getContractid())){
                String uuid=kv.getUuid();
                AppletsBusinessVideoSigncoor appletsBusinessVideoSigncoor = new AppletsBusinessVideoSigncoor();
                appletsBusinessVideoSigncoor.setUuid(uuid);
                appletsBusinessVideoSigncoor.setState("0");
                appletsBusinessVideoSigncoor.setSignuserid(appletsApplicantUser.getId());
                List<AppletsBusinessVideoSigncoor>  appletsBusinessVideoSigncoorList= appletsBusinessVideoSigncoorService.selectAppletsBusinessVideoSigncoorList(appletsBusinessVideoSigncoor);
                if (!StringUtils.isEmpty(appletsBusinessVideoSigncoorList) ){
                    contratid=kv.getContractid();
                    break;
                }
            }
        }
        if (!"".equals(contratid)){
            BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(openidView.getConfigId())),BasicView.class);
            QysView qysView=basicView.getQys();
            if (StringUtils.isNull(qysView)){
                return Result.cloud_602("契约锁未配置!");
            }
            SdkClient client = new SdkClient(qysView.getUrl(), qysView.getAccesskey(), qysView.getAccessSecret());
            QysUser qysUser= new QysUser();
            qysUser.setName(appletsApplicantUser.getName());
            qysUser.setCertificatesnumber(appletsApplicantUser.getCertificatesnumber());
            if (!"".equals(StringUtils.isHcNull(appletsApplicantUser.getPhone(),""))){
                qysUser.setType("1");
            }else{
                qysUser.setType("2");
            }
            qysUser.setPhone(appletsApplicantUser.getPhone());
            qysUser.setMailbox(appletsApplicantUser.getMailbox());
            msg= SendByCodeSetting.getKeyHks(client,Long.valueOf(contratid),qysUser);
        }else{
            return Result.cloud_602("没有待签署的文书!");
        }
        return Result.success("操作成功",msg);
    }

    //预约保存
    @PostMapping("/setAppointment")
    public Result setAppointment(@RequestBody AppletsBusinessReserve appletsBusinessReserve) throws  Exception
    {
        String openid = StringUtils.isHcNull(appletsBusinessReserve.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String businessId=SerialNumberUtils.getSerialNumber(NumbereEnum.SYS_APPLETS_APPOINTMENT_NUMBER);
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        appletsBusinessReserve.setAppointmentnumber(businessId);
        appletsBusinessReserve.setConfigId(openidView.getConfigId());
        appletsBusinessReserve.setDeptId(openidView.getDeptId());
        appletsBusinessReserve.setAreatype(openidView.getAreatype());
        appletsBusinessReserve.setSubmitter(openidView.getRealName());
        appletsBusinessReserve.setReviewerresult("0");
        appletsBusinessReserve.setCategory(appletsBusinessReserve.getCategory().replace("\"", ""));
        appletsBusinessReserve.setMatter(appletsBusinessReserve.getMatter().replace("\"", ""));
        appletsBusinessReserve.setPurpose(appletsBusinessReserve.getPurpose().replace("\"", ""));
        appletsBusinessReserve.setPlace(appletsBusinessReserve.getPlace().replace("\"", ""));
        appletsApplicantUserLogService.insertLong(openid,"在平台完成预约申请操作，预约号为【"+businessId+"】。");
        return toResult(appletsBusinessReserveService.insertAppletsBusinessReserve(appletsBusinessReserve));
    }

    //预约保存-网站端
    @PostMapping("/setWebAppointment")
    public Result setWebAppointment(@RequestBody AppletsBusinessReserve appletsBusinessReserve) throws  Exception
    {
        String openid = StringUtils.isHcNull(appletsBusinessReserve.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String businessId=SerialNumberUtils.getSerialNumber(NumbereEnum.SYS_APPLETS_APPOINTMENT_NUMBER);
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        Map<String,String> categoryHt= new HashMap<String,String>();
        List<SysDictData> categoryList=dictTypeService.selectDictDataByType(ComUtil.CONFIG_CATEGORY);
        categoryList.forEach(kv->{
            categoryHt.put(kv.getDictValue(),kv.getDictLabel());
        });
        String appointmentdate = appletsBusinessReserve.getAppointmentdate();
        if (appointmentdate.length()>14){
            appletsBusinessReserve.setAppointmentdate(appointmentdate.substring(0,10));
            appletsBusinessReserve.setAppointmenttime(appointmentdate.substring(11,16));
        }
        appletsBusinessReserve.setAppointmentnumber(businessId);
        appletsBusinessReserve.setConfigId(openidView.getConfigId());
        appletsBusinessReserve.setDeptId(openidView.getDeptId());
        appletsBusinessReserve.setAreatype(openidView.getAreatype());
        appletsBusinessReserve.setSubmitter(openidView.getWechatPhone());
        appletsBusinessReserve.setReviewerresult("0");
        appletsBusinessReserve.setCategory(categoryHt.get(appletsBusinessReserve.getCategory()));
        appletsBusinessReserve.setMatter(appletsBusinessReserve.getMatter().replace("\"", ""));
        appletsBusinessReserve.setPurpose(appletsBusinessReserve.getPurpose().replace("\"", ""));
        appletsBusinessReserve.setPlace(appletsBusinessReserve.getPlace().replace("\"", ""));
        appletsApplicantUserLogService.insertLong(openid,"在平台完成预约申请操作，预约号为【"+businessId+"】。");
        return toResult(appletsBusinessReserveService.insertAppletsBusinessReserve(appletsBusinessReserve));
    }

    //预约取消
    @PostMapping("/removeAppointment")
    public Result removeAppointment(@RequestBody WechatView wechatView) throws  Exception
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        if (StringUtils.isNull(wechatView.getAppointmentId())){
            return Result.cloud_602("appointmentId不能为空");
        }
        AppletsBusinessReserve appletsBusinessReserve = new AppletsBusinessReserve(wechatView.getAppointmentId());
        appletsBusinessReserve.setReviewerresult("3");
        appletsApplicantUserLogService.insertLong(openid,"在平台取消了预约申请，预约号为【"+appletsBusinessReserve.getAppointmentnumber()+"】。");
        return toResult(appletsBusinessReserveService.updateAppletsBusinessReserve(appletsBusinessReserve));
    }

    //预约列表
    @PostMapping("/getAppointmentList")
    public Result getAppointmentList(@RequestBody WechatView wechatView) throws  Exception
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        AppletsBusinessReserve appletsBusinessReserve = new AppletsBusinessReserve();
        appletsBusinessReserve.setOpenid(openid);
        List<AppletsBusinessReserve> appletsBusinessReserveList=appletsBusinessReserveService.selectAppletsBusinessReserveList(appletsBusinessReserve);
        return Result.success(appletsBusinessReserveList);
    }

    //预约详情
    @PostMapping("/getAppointmentDetails")
    public Result getAppointmentDetails(@RequestBody WechatView wechatView) throws  Exception
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        if (StringUtils.isNull(wechatView.getAppointmentId())){
            return Result.cloud_602("appointmentId不能为空");
        }
        AppletsBusinessReserve appletsBusinessReserve = new AppletsBusinessReserve(wechatView.getAppointmentId());
        return Result.success(appletsBusinessReserve);
    }

    //咨询保存-网站端
    @PostMapping("/setWebConsulting")
    public Result setWebConsulting(@RequestBody AppletsBusinessConsulting appletsBusinessConsulting) throws  Exception
    {
        String openid = StringUtils.isHcNull(appletsBusinessConsulting.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        String businessId=SerialNumberUtils.getSerialNumber(NumbereEnum.SYS_WEBSITE_CONSULTING_NUMBER);
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        appletsBusinessConsulting.setConsultingnumber(businessId);
        appletsBusinessConsulting.setConfigId(openidView.getConfigId());
        appletsBusinessConsulting.setDeptId(openidView.getDeptId());
        appletsBusinessConsulting.setAreatype(openidView.getAreatype());
        appletsBusinessConsulting.setSubmitter(openidView.getWechatPhone());
        appletsBusinessConsulting.setState("0");
        appletsApplicantUserLogService.insertLong(openid,"在平台完成咨询申请操作，咨询号为【"+businessId+"】。");
        return toResult(appletsBusinessConsultingService.insertAppletsBusinessConsulting(appletsBusinessConsulting));
    }


    //咨询-网站端首页列表
    @PostMapping("/getHomeConsultingList")
    public Result getHomeConsultingList(@RequestBody WechatView wechatView) throws  Exception
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        AppletsBusinessConsulting appletsBusinessConsulting = new AppletsBusinessConsulting();
        appletsBusinessConsulting.setConfigId(appletsConfig.getId());
        appletsBusinessConsulting.setDeptId(appletsConfig.getDeptId());
        appletsBusinessConsulting.setState("1");
        appletsBusinessConsulting.setIspublic("true");
        List<AppletsBusinessConsulting> list = appletsBusinessConsultingService.selectAppletsBusinessConsultingList(appletsBusinessConsulting);
        list.forEach(kv->{
            kv.setConfigId(null);
            kv.setDeptId(null);
        });
        if (list.size()>4){
            list = list.subList(0,4);
        }
        list.sort(Comparator.comparing(AppletsBusinessConsulting::getReviewerdatetime).reversed());
        return Result.success(list);
    }


    //咨询-网站端查看列表
    @PostMapping("/getHomeSeeConsultingList")
    public TableDataInfo getHomeSeeConsultingList(@RequestBody WebSiteView webSiteView) throws  Exception
    {
        String appid = StringUtils.isHcNull(webSiteView.getAppid(),"");
        if("".equals(appid)){
            return null;
        }
        startWebPage(webSiteView.getPageNum(),webSiteView.getPageSize());
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        AppletsBusinessConsulting appletsBusinessConsulting = new AppletsBusinessConsulting();
        appletsBusinessConsulting.setConfigId(appletsConfig.getId());
        appletsBusinessConsulting.setDeptId(appletsConfig.getDeptId());
        appletsBusinessConsulting.setState("1");
        appletsBusinessConsulting.setIspublic("true");
        List<AppletsBusinessConsulting> list = appletsBusinessConsultingService.selectAppletsBusinessConsultingList(appletsBusinessConsulting);
        list.sort(Comparator.comparing(AppletsBusinessConsulting::getReviewerdatetime).reversed());
        return getDataTable(list);
    }

    //咨询列表
    @PostMapping("/getConsultingList")
    public Result getConsultingList(@RequestBody WechatView wechatView) throws  Exception
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        AppletsBusinessConsulting appletsBusinessConsulting = new AppletsBusinessConsulting();
        appletsBusinessConsulting.setOpenid(openid);
        List<AppletsBusinessConsulting> appletsBusinessConsultingList = appletsBusinessConsultingService.selectAppletsBusinessConsultingList(appletsBusinessConsulting);
        return Result.success(appletsBusinessConsultingList);
    }


    /*****************************网站端注册登录***************************************/
    //发送手机验证码
    @PostMapping("/sendWebPhoneCode")
    public Result sendWebPhoneCode(@RequestBody WebSiteIntoView webSiteIntoView) throws  Exception
    {
        String appid = StringUtils.isHcNull(webSiteIntoView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        String phone = StringUtils.isHcNull(webSiteIntoView.getPhone(),"");
        if("".equals(phone)){
            return Result.cloud_602("手机号不能为空!");
        }
        if (!PhoneFormatCheckUtils.isPhoneLegal(phone.trim())){
            return Result.cloud_602("手机号格式不正确!");
        }
        String message =redisCache.getCacheObject(ComUtil.getWebSiteCodeCacheKey(phone));
        if (!"".equals(StringUtils.isHcNull(message,""))){
            return Result.cloud_602("您的验证码还在有效期内，请勿重新获取!");
        }
        List<String> phonelist = new ArrayList<String>();
        phonelist.add("+86"+phone);
        GlobalView globalView = new GlobalView();
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        String code = ComUtil.getRandom(6);
        wxSendTplMessageService.sendAddOrder(phonelist, configId, "9",code,"5","");
        redisCache.setCacheObject(ComUtil.getWebSiteCodeCacheKey(phone),code, 5, TimeUnit.MINUTES);//缓存网站验证码
        return Result.success();
    }

    //网站注册
    @PostMapping("/webSiteRegister")
    public Result webSiteRegister(@RequestBody WebSiteIntoView webSiteIntoView) throws  Exception
    {
        String appid = StringUtils.isHcNull(webSiteIntoView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        String phone = StringUtils.isHcNull(webSiteIntoView.getPhone(),"");
        if("".equals(phone)){
            return Result.cloud_602("手机号不能为空");
        }
        String code = StringUtils.isHcNull(webSiteIntoView.getCode(),"");
        if("".equals(phone)){
            return Result.cloud_602("手机验证码不能为空");
        }
        String message =redisCache.getCacheObject(ComUtil.getWebSiteCodeCacheKey(phone));
        if ("".equals(StringUtils.isHcNull(message,""))){
            return Result.cloud_602("手机验证码已失效");
        }
        if (!code.equals(message)){
            return Result.cloud_602("手机验证码不正确");
        }
        String uuid=IdUtils.simpleUUID();
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        WebWebsiteUser webWebsiteUser = new WebWebsiteUser();
        webWebsiteUser.setDeptId(appletsConfig.getDeptId());
        webWebsiteUser.setConfigId(appletsConfig.getId());
        webWebsiteUser.setPhone(phone);
        List<WebWebsiteUser> webWebsiteUserList=webWebsiteUserService.selectWebWebsiteUserList(webWebsiteUser);
        if (!StringUtils.isEmpty(webWebsiteUserList) ){
            return Result.cloud_602("手机号已注册!");
        }
        webWebsiteUser.setWebId(uuid);
        webWebsiteUser.setPassword(WebDecodeUtil.Encrypt(webSiteIntoView.getPassword()));
        OpenidView openidView = new OpenidView();
        int rows = webWebsiteUserService.insertWebWebsiteUser(webWebsiteUser);
        if (rows>0){
            AppletsApplicantUser appletsApplicantUser = new AppletsApplicantUser();
            appletsApplicantUser.setOpenid(uuid);
            appletsApplicantUser.setConfigId(appletsConfig.getId());
            appletsApplicantUser.setDeptId(appletsConfig.getDeptId());
            appletsApplicantUser.setIsself("TRUE");
            appletsApplicantUser.setUsertype("1");
            appletsApplicantUser.setPhone(phone);
            appletsApplicantUser.setAreatype("2");
            appletsApplicantUserService.insertAppletsApplicantUser(appletsApplicantUser);
            openidView = appletsApplicantUserService.getOpenidWebView(uuid,true);
            appletsApplicantUserLogService.insertLong(uuid,"登录网站");
        }
        return Result.success(openidView);
    }

    //网站忘记密码
    @PostMapping("/webSiteForgetPassWord")
    public Result webSiteForgetPassWord(@RequestBody WebSiteIntoView webSiteIntoView) throws  Exception
    {
        String appid = StringUtils.isHcNull(webSiteIntoView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        String phone = StringUtils.isHcNull(webSiteIntoView.getPhone(),"");
        if("".equals(phone)){
            return Result.cloud_602("手机号不能为空");
        }
        String code = StringUtils.isHcNull(webSiteIntoView.getCode(),"");
        if("".equals(phone)){
            return Result.cloud_602("手机验证码不能为空");
        }
        String message =redisCache.getCacheObject(ComUtil.getWebSiteCodeCacheKey(phone));
        if ("".equals(StringUtils.isHcNull(message,""))){
            return Result.cloud_602("手机验证码已失效");
        }
        if (!code.equals(message)){
            return Result.cloud_602("手机验证码不正确");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        WebWebsiteUser oldWebWebsiteUser = new WebWebsiteUser();
        oldWebWebsiteUser.setDeptId(appletsConfig.getDeptId());
        oldWebWebsiteUser.setConfigId(appletsConfig.getId());
        oldWebWebsiteUser.setPhone(phone);
        List<WebWebsiteUser> webWebsiteUserList=webWebsiteUserService.selectWebWebsiteUserList(oldWebWebsiteUser);
        if (StringUtils.isEmpty(webWebsiteUserList) ){
            return Result.cloud_602("手机号未注册!");
        }
        WebWebsiteUser webWebsiteUser = webWebsiteUserList.get(0);
        String uuid=webWebsiteUser.getWebId();
        webWebsiteUser.setPassword(WebDecodeUtil.Encrypt(webSiteIntoView.getPassword()));
        int rows = webWebsiteUserService.updateWebWebsiteUser(webWebsiteUser);
        OpenidView openidView = new OpenidView();
        if (rows>0){
            openidView = appletsApplicantUserService.getOpenidWebView(uuid,true);
        }
        return Result.success(openidView);
    }

    //网站登录
    @PostMapping("/webLogin")
    public Result webLogin(@RequestBody WebSiteIntoView webSiteIntoView) throws  Exception
    {
        String appid = StringUtils.isHcNull(webSiteIntoView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        String phone = StringUtils.isHcNull(webSiteIntoView.getPhone(),"");
        if("".equals(phone)){
            return Result.cloud_602("手机号不能为空");
        }
        String password = StringUtils.isHcNull(webSiteIntoView.getPassword(),"");
        if("".equals(password)){
            return Result.cloud_602("密码不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        WebWebsiteUser oldWebWebsiteUser = new WebWebsiteUser();
        oldWebWebsiteUser.setDeptId(appletsConfig.getDeptId());
        oldWebWebsiteUser.setConfigId(appletsConfig.getId());
        oldWebWebsiteUser.setPhone(phone);
        List<WebWebsiteUser> webWebsiteUserList=webWebsiteUserService.selectWebWebsiteUserList(oldWebWebsiteUser);
        if (StringUtils.isEmpty(webWebsiteUserList) ){
            return Result.cloud_602("手机号未注册!");
        }
        WebWebsiteUser webWebsiteUser = webWebsiteUserList.get(0);
        if (!password.equals(WebDecodeUtil.Decrypt(webWebsiteUser.getPassword()))){
            return Result.cloud_602("密码输入错误!");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidWebView(webWebsiteUser.getWebId(),true);
        return Result.success(openidView);
    }

    //验证手机号是否注册
    @PostMapping("/isWebSitePhoneRegister")
    public Result isWebSitePhoneRegister(@RequestBody WebSiteIntoView webSiteIntoView) throws  Exception
    {
        String appid = StringUtils.isHcNull(webSiteIntoView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        String phone = StringUtils.isHcNull(webSiteIntoView.getPhone(),"");
        if("".equals(phone)){
            return Result.cloud_602("手机号不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        WebWebsiteUser webWebsiteUser = new WebWebsiteUser();
        webWebsiteUser.setDeptId(appletsConfig.getDeptId());
        webWebsiteUser.setConfigId(appletsConfig.getId());
        webWebsiteUser.setPhone(phone);
        List<WebWebsiteUser> webWebsiteUserList=webWebsiteUserService.selectWebWebsiteUserList(webWebsiteUser);
        if (!StringUtils.isEmpty(webWebsiteUserList) ){
            return Result.cloud_602("手机号已注册!");
        }
        return Result.success();
    }


    //网站修改密码
    @PostMapping("/webChangePassWord")
    public Result webChangePassWord(@RequestBody WebSiteIntoView webSiteIntoView) throws  Exception
    {
        String openid = StringUtils.isHcNull(webSiteIntoView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        WebWebsiteUser webWebsiteUser =  webWebsiteUserService.selectWebWebsiteUserById(openid);
        String  oldPassword = webSiteIntoView.getOldPassword();
        if (!oldPassword.equals(WebDecodeUtil.Decrypt(webWebsiteUser.getPassword()))){
            return Result.cloud_602("原密码输入错误!");
        }
        webWebsiteUser.setPassword(WebDecodeUtil.Encrypt(webSiteIntoView.getPassword()));
        return toResult(webWebsiteUserService.updateWebWebsiteUser(webWebsiteUser));
    }

    public static void main(String[] args) {
        System.out.println(WebDecodeUtil.Decrypt("c6a65e3d031a151713232819295d5f4853"));
    }
}
